package heterogeneousContainers;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 8/30/12
 * Time: 2:49 PM
 *
 */
public class Row {

    Map<Column<?>,Object> rowMap;

    public Row() {
        rowMap = new HashMap<Column<?>, Object>();
    }

    public <T> void putColumn(Column<T> column, T columnValue){
        rowMap.put(column,columnValue);
    }

    public <T> T getColumnValue(Column<T> column){

        return column.cast(rowMap.get(column));
    }

    @Override
    public String toString() {
        return "Row{" +
                "rowMap=" + rowMap +
                '}';
    }

    public static void main(String[] args) {

        Row row = getNameAndAgeRow();

        System.out.println(row);

        System.out.println(row.getColumnValue(new Column<Integer>(Integer.class,"age")));

        row = maliciouslyGetNameAndAgeRow();

        System.out.println(row);

        //row.getColumnValue(new Column(Integer.class,"age"));
    }

    private static Row getNameAndAgeRow() {
        Row row = new Row();
        row.putColumn(new Column<String>(String.class,"name"),"Mathew");
        row.putColumn(new Column<Integer>(Integer.class,"age"),20);
        return row;
    }

    //if someone uses our class as raw we can't guarantee type safety anymore, just like in the case of java containers
    private static Row maliciouslyGetNameAndAgeRow() {
        Row row = new Row();
        row.putColumn(new Column(String.class,"name"),"Mathew");
        row.putColumn(new Column(Integer.class,"age"),"20");
        return row;
    }
}
